package com.lv.suyiyong.hfr.ui

import android.graphics.Color
import android.graphics.Typeface
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.FactoryContainerPagerAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.animateTabToHorizontal
import com.lv.common.ktx.animateTabToVertical
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DensityUtil
import com.lv.common.utils.StatusBarUtil
import com.lv.service.bean.ADBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityLocationFactoryTabBinding
import com.lv.suyiyong.hfr.fragment.LocationFactoryTabFragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.math.abs

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：本地工厂榜
 */
@Route(path = ARoutUtils.FactoryLocationTabActivity)
class FactoryLocationTabActivity : BaseActivity<ActivityLocationFactoryTabBinding>() {
    private val mBannerTopData = mutableListOf<CommonSelectedBean>()
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mAdapter: FactoryContainerPagerAdapter? = null
    private var mPosition = 0
    private var mTabLinearLayout: LinearLayout? = null
    private var threshold = 0
    private val mTopUrl =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/hengfuran/bzgc.png?x-oss-process=image/format,webp"
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/localFacNav.png"
    private var mUserInfo: UserInfo? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_location_factory_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@FactoryLocationTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
            val statusBarHeight =
                StatusBarUtil.getStatusBarHeight(this@FactoryLocationTabActivity) + DensityUtil.dip2px(
                    this@FactoryLocationTabActivity,
                    42.0f
                )
            threshold =
                DensityUtil.dip2px(this@FactoryLocationTabActivity, 163.0f) - statusBarHeight
            collToolbar.minimumHeight =
                threshold - StatusBarUtil.getStatusBarHeight(this@FactoryLocationTabActivity)
        }
    }


    override fun initConfig() {
        super.initConfig()
        findAllBanner()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        mBinding.ivTop.LoadSrc(mTopUrl)
//        initBannerAdapter()
//        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(
                    CommonSelectedBean(
                        "推荐工厂", postiont = 0, selected = true,
                        tag = "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/newsu/shangpin/%E6%9C%BA%E7%94%B5%E8%AE%BE%E5%A4%87/%E7%94%B5%E6%9C%BA.png"
                    )
                )
                mAllCategory?.forEach {
                    mTabs.add(
                        CommonSelectedBean(it.name, postiont = it.fcaid ?: 0, tag = it.image ?: "")
                    )
                }
            }
            taskCategory.await()
            initPage()
        }

        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }

    private suspend fun getCategoryForDB(): List<CategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取商品分类
            CategoryDbHelper.getFindAllCategorySuspend(this@FactoryLocationTabActivity)
        }
    }

    private fun initViewPager() {

        mAdapter = FactoryContainerPagerAdapter(
            supportFragmentManager, lifecycle,
            mTabs
        )
        mAdapter?.listener = object : FactoryContainerPagerAdapter.CirTabListener {
            override fun getFragment(position: Int): Fragment {
                val fragment = LocationFactoryTabFragment.newInstance(mTabs[position].postiont)
                return fragment
            }
        }

        mBinding.viewpager.adapter = mAdapter
        mBinding.viewpager.offscreenPageLimit = mTabs.size
//        mBinding.tabLayout.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[0].name ?: ""
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding.tabLayout.getTabAt(0)?.text = spannedString
        TabLayoutMediator(
            mBinding.tabLayout, mBinding.viewpager
        ) { tabLayout, position ->
//            // 设置Tab的标题
            val customView =
                tabLayout.setCustomView(R.layout.tab_location_factory)
            val tvTabTitle = customView.customView?.findViewById<TextView>(R.id.tv_name)
            val ivTabImage = customView.customView?.findViewById<ImageView>(R.id.iv_img)
            ivTabImage?.LoadSrc(mTabs[position].tag)
            tvTabTitle?.paint?.isFakeBoldText = position == mPosition
            tvTabTitle?.text = mTabs[position].name
            tvTabTitle?.textSize = if (position == mPosition) 15.0f else 13.0f
            tvTabTitle?.setTextColor(Color.parseColor(if (position == mPosition) "#FF8400" else "#333333"))
        }.attach()
        mBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val position = tab?.position
                for (i in 0 until mBinding.tabLayout.tabCount) {
                    val tvTabTitle =
                        mBinding.tabLayout.getTabAt(i)?.customView?.findViewById<TextView>(R.id.tv_name)
                    tvTabTitle?.paint?.isFakeBoldText = position == i
                    tvTabTitle?.textSize = if (position == i) 15.0f else 13.0f
                    tvTabTitle?.setTextColor(Color.parseColor(if (position == i) "#FF8400" else "#333333"))

                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

    }


    override fun initEvents() {
        super.initEvents()
        mBinding.appBar.setupAppBarLayoutListener { state ->
            when (state) {
                AppBarState.EXPANDED -> {
                    // 展开状态，比如显示 FAB 或设置标题
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
//                    setOrientation(true)
                }

                AppBarState.COLLAPSED -> {
                    // 折叠状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_cir_white)
//                    setOrientation(false)
                }

                AppBarState.PARTIALLY_COLLAPSED -> {
                    // 中间状态
                    mBinding.tabLayout.setBackgroundResource(com.lv.common.R.drawable.bg_half_t_white_10)
//                    setOrientation(true)
                }
            }

        }
        val baseH = DensityUtil.dip2px(this@FactoryLocationTabActivity, 43.0f)
        val chengH = DensityUtil.dip2px(this@FactoryLocationTabActivity, 32.0f)
        val tabLayoutParams = mBinding.tabLayout.layoutParams as AppBarLayout.LayoutParams
        mBinding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val abs = abs(verticalOffset)
            var mAlpha: Float = abs * 1.0f / threshold
            if (mAlpha <= 0) {
                mAlpha = 0.0f
            }
            if (mAlpha >= 1) {
                mAlpha = 1.0f
                setOrientation(false, mAlpha)
            } else {
                setOrientation(true, mAlpha)
            }
            tabLayoutParams.height = baseH + ((1 - mAlpha) * chengH).toInt()
            mBinding.tabLayout.layoutParams = tabLayoutParams
            mBinding.ivTitlePage.alpha = mAlpha
            mBinding.viewStatus.alpha = mAlpha
        })

    }

    private var mOrientationStatus = true
    private fun setOrientation(orientation: Boolean, mAlpha: Float) {

        val tabCount = mBinding.tabLayout.tabCount
        val baseH = DensityUtil.dip2px(this@FactoryLocationTabActivity, 23.0f)
        val changeH = DensityUtil.dip2px(this@FactoryLocationTabActivity, 6.0f)
        for (tab in 0 until tabCount) {
            val customView = mBinding.tabLayout.getTabAt(tab)?.customView
            val mLLTab =
                customView?.findViewById<LinearLayout>(R.id.ll_tab)
            val imageView = customView?.findViewById<ImageView>(R.id.iv_img)
            val layoutParams = imageView?.layoutParams as LinearLayout.LayoutParams
            val height = baseH + ((1 - mAlpha) * changeH).toInt()
            layoutParams.height = height
            layoutParams.width = height
            imageView.layoutParams = layoutParams
            if (orientation == mOrientationStatus) {
                continue
            }
            if (orientation) {
                mLLTab?.animateTabToVertical()
            } else {
                mLLTab?.animateTabToHorizontal()
            }
        }
        mOrientationStatus = orientation
    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        initViewPager()
    }

    private fun findAllBanner() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findAllBanner("1") }.await()
            parseFindAllBannerResult(result)
        }
    }

    private fun parseFindAllBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<List<ADBean>> { code, data, message, result ->
                LogUtils.e("aaa")
                val adBean = data?.get(0)
                mBinding.ivTop.LoadSrc(adBean?.image)
            }
            onBizError<Any> { code, message, data ->
            }
        }
        data.onFailure {

        }
    }


}